package com.genewoo.jta.plugin;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

import de.mud.jta.FilterPlugin;
import de.mud.jta.Plugin;
import de.mud.jta.PluginBus;
import de.mud.jta.VisualPlugin;

public class Player extends Plugin implements FilterPlugin, VisualPlugin, Runnable{
	
	
	private JMenu menu;
	
	private Thread t;
	
	private long starttime;
	

	private class LoadFile implements Runnable {

		public void run() {
			try {
				Thread.currentThread().sleep(1000);
				starttime = starttime + 1000;
			    BufferedReader in = new BufferedReader(new FileReader("d:\\test2.log"));
			    String str = "";
			    
			
		        while ((str = in.readLine()) != null) {
		        	System.out.println(str);
		        	source.write(getKey(str));
		        }
		        in.close();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}

		private byte[] getKey(String str) {
			String time = str.split(":")[0];
			String key = str.split(":")[1];
			long timeLong = Long.parseLong(time);
			while(timeLong > (System.currentTimeMillis() - starttime)) {
				Thread.yield();
			}
			byte keyByte = Byte.parseByte(key);			
			return new byte[]{keyByte};
		}
		
	}
	public Player(PluginBus bus, String id) {
		super(bus, id);

		
		menu = new JMenu("Player");
		JMenuItem play = new JMenuItem("Play");
		play.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				
				
				starttime = System.currentTimeMillis();
				t = new Thread(new LoadFile());
				
				t.start();
				
			
			}
			
		});
		menu.add(play);
//	    bus.registerPluginListener(new TelnetCommandListener(){
//
//			public void sendTelnetCommand(byte command) throws IOException {
//				System.out.println(command);
//				
//			}
//	    	
//	    }
//	    );
		// TODO Auto-generated constructor stub
	}

	  protected FilterPlugin source;

	  public void setFilterSource(FilterPlugin source) {
		System.out.println(source);
	    this.source = source;
	  }

	  public FilterPlugin getFilterSource() {
	    return source;
	  }

	  public int read(byte[] b) throws IOException {
//		System.out.println(b);
		return source.read(b);
	  }

	  public void write(byte[] b) throws IOException {
//		System.out.println(b);
	    source.write(b);
	  }

	public JComponent getPluginVisual() {
		// TODO Auto-generated method stub
		return null;
	}

	public JMenu getPluginMenu() {
		return menu;
	}
	

	public void run() {
				
	}





}
